<script setup lang="tsx">
import { ref, unref, reactive } from 'vue'
import { ElSwitch } from 'element-plus'

import { BaseButton } from '@/components/Button'
import { ContentWrap } from '@/components/ContentWrap'
import { Dialog } from '@/components/Dialog'
import { Table } from '@/components/Table'

import { useI18n } from '@/hooks/web/useI18n'
import { useTable } from '@/hooks/web/useTable'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'

import {
  getDepartmentTreeApi,
  saveDepartmentApi,
  deleteDepartmentApi
} from '@/api/Admin/auth/department'
import type { DepartmentItem } from '@/api/Admin/auth/department/types'
import Write from './components/Write.vue'

const ids = ref<string[]>([])

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const res = await getDepartmentTreeApi({})
    return {
      list: res.data || [],
      total: res.count || 0
    }
  },
  fetchDelApi: async () => {
    const res = await deleteDepartmentApi(unref(ids))
    return !!res
  }
})
const { loading, dataList } = tableState
const { getList, getElTableExpose, delList } = tableMethods

const { t } = useI18n()

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'parent_id',
    label: t('admin.dept.parent'),
    search: {
      hidden: true
    },
    table: {
      hidden: true
    },
    form: {
      component: 'TreeSelect',
      componentProps: {
        nodeKey: 'id',
        props: {
          label: 'name'
        }
      },
      optionApi: async () => {
        const res = await getDepartmentTreeApi({})
        return res.data
      }
    },
    detail: {
      slots: {
        default: (data: any) => {
          return <>{data.parent_id}</>
        }
      }
    }
  },
  {
    field: 'name',
    label: t('admin.dept.name'),
    table: {
      slots: {
        default: (data: any) => {
          return <>{data.row.name}</>
        }
      }
    }
  },
  {
    field: 'dept_key',
    label: t('admin.dept.deptKey'),
    search: {
      hidden: true
    }
  },
  {
    field: 'owner',
    label: t('admin.dept.owner'),
    search: {
      hidden: true
    }
  },
  {
    field: 'phone',
    label: t('common.info.phone'),
    search: {
      hidden: true
    }
  },
  {
    field: 'email',
    label: t('common.info.email'),
    search: {
      hidden: true
    }
  },
  {
    field: 'order',
    label: t('common.status.order'),
    search: {
      hidden: true
    },
    form: {
      component: 'InputNumber'
    }
  },
  {
    field: 'disabled',
    label: t('common.status.disabled'),
    search: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          const row = data.row
          return (
            <>
              <ElSwitch modelValue={row.disabled} disabled />
            </>
          )
        }
      }
    },
    form: {
      component: 'Select',
      componentProps: {
        options: [
          {
            value: true,
            label: t('common.disable')
          },
          {
            value: false,
            label: t('common.enable')
          }
        ]
      }
    },
    detail: {
      slots: {
        default: (data: any) => {
          return <>{!data.disabled ? t('common.status.enable') : t('common.status.disable')}</>
        }
      }
    }
  },
  {
    field: 'desc',
    label: t('common.info.desc'),
    search: {
      hidden: true
    },
    form: {
      component: 'Input',
      componentProps: {
        type: 'textarea',
        rows: 5
      },
      colProps: {
        span: 24
      }
    },
    detail: {
      slots: {
        default: (data: any) => {
          return <>{data.desc}</>
        }
      },
      span: 24
    }
  },
  {
    field: 'action',
    width: '260px',
    label: t('common.action.title'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <BaseButton type="primary" link size="small" onClick={() => action(data.row, 'edit')}>
                {t('common.action.edit')}
              </BaseButton>
              <BaseButton
                type="success"
                link
                size="small"
                onClick={() => action(data.row, 'detail')}
              >
                {t('common.action.detail')}
              </BaseButton>
              <BaseButton
                type="danger"
                link
                loading={delLoading.value}
                size="small"
                onClick={() => delData(data.row)}
              >
                {t('common.action.delete')}
              </BaseButton>
            </>
          )
        }
      }
    }
  }
])

// @ts-ignore
const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref<DepartmentItem | null>(null)
const actionType = ref('')

const AddAction = () => {
  dialogTitle.value = t('common.dialog.add')
  currentRow.value = null
  dialogVisible.value = true
  actionType.value = ''
}

const delLoading = ref(false)

const delData = async (row: DepartmentItem | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row
    ? [row.id]
    : elTableExpose?.getSelectionRows().map((v: DepartmentItem) => v.id) || []
  delLoading.value = true
  await delList(true, unref(ids)).finally(() => {
    delLoading.value = false
  })
}

const action = (row: DepartmentItem, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'common.dialog.edit' : 'common.dialog.detail')
  actionType.value = type
  currentRow.value = row
  dialogVisible.value = true
}

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    const res = await saveDepartmentApi(formData)
      .catch(() => {})
      .finally(() => {
        saveLoading.value = false
      })
    if (res) {
      dialogVisible.value = false
      getList()
    }
  }
}
</script>

<template>
  <ContentWrap>
    <div class="mb-10px">
      <BaseButton type="primary" @click="AddAction">{{ t('component.button.add') }}</BaseButton>
    </div>

    <Table
      showAction
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      @register="tableRegister"
      @refresh="getList"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write
      v-if="actionType !== 'detail'"
      ref="writeRef"
      :form-schema="allSchemas.formSchema"
      :current-row="currentRow"
    />
    <Write
      v-if="actionType === 'detail'"
      ref="writeRef"
      :form-schema="allSchemas.formSchema"
      :current-row="currentRow"
      disabled
    />

    <template #footer>
      <BaseButton
        v-if="actionType !== 'detail'"
        type="primary"
        :loading="saveLoading"
        @click="save"
      >
        {{ t('component.button.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('component.button.close') }}</BaseButton>
    </template>
  </Dialog>
</template>
